using Microsoft.Win32;
using System;
using System.Collections.Generic;
using System.IO;
using System.Text;
using System.Text.Json;
using System.Windows;
using WpfApp_ChenxiConsole.FileIO;
using WpfApp_ChenxiConsole.TCP;

namespace WpfApp_ChenxiConsole.OTA
{
    /// <summary>
    /// EcuOtaConfigWindow.xaml 的交互逻辑
    /// </summary>
    public partial class EcuOtaConfigWindow : Window
    {
        private FileLoader _fileLoader;
        private EcuOtaConfig _currentConfig;
        private TcpConsoleControl? _tcpConsoleControl; // TCP客户端控件
        private string? _tcpClientTabHeader; // 绑定的TCP客户端选项卡标题

        // 固件升级状态枚举
        private enum FirmwareUpgradeState
        {
            Ready,
            NotifyingEcu,
            ErasingFlash,
            SendingData,
            VerifyingData,
            Resetting,
            Completed,
            Failed
        }

        // 固件升级相关成员变量
        private FirmwareUpgradeState _currentUpgradeState = FirmwareUpgradeState.Ready;
        private System.Windows.Threading.DispatcherTimer? _upgradeStateMachineTimer;
        private List<string> _receivedResponses = new List<string>();
        private int _lastProcessedIndex = -1; // 记录最后处理的消息索引
        private int _currentCommandRetryCount = 0; // 当前命令的重试次数
        private const int MAX_RETRY_COUNT = 3; // 最大重试次数
        private string _messageHandlerId = Guid.NewGuid().ToString();

        // 数据流发送相关成员变量
        private byte[] _firmwareData = Array.Empty<byte>(); // 固件文件的二进制数据
        private int _currentPacketIndex = 0; // 当前发送的包索引（从0开始）
        private int _totalPacketCount = 0; // 总包数
        private const int DATA_PACKET_SIZE = 256; // 每包数据大小（字节）
        
        // 升级进度跟踪相关成员变量
        private DateTime _upgradeStartTime; // 升级开始时间
        private int _totalJsonPackageCount; // 总JSON包数（从第一步到第五步的回包）

        /// <summary>
        /// 默认构造函数，不绑定TCP客户端
        /// </summary>
        public EcuOtaConfigWindow()
        {
            InitializeComponent();
            _fileLoader = new FileLoader();
            _currentConfig = new EcuOtaConfig();
            DataContext = _currentConfig;
            
            // 初始化TCP客户端状态显示
            UpdateTcpClientStatus();
            
            // 初始化升级状态机定时器
            InitializeUpgradeStateMachine();
        }

        /// <summary>
        /// 构造函数，绑定TCP客户端
        /// </summary>
        /// <param name="tcpConsoleControl">TCP客户端控件</param>
        /// <param name="tabHeader">TCP客户端选项卡标题</param>
        public EcuOtaConfigWindow(TcpConsoleControl? tcpConsoleControl, string? tabHeader = null)
        {
            InitializeComponent();
            _fileLoader = new FileLoader();
            _currentConfig = new EcuOtaConfig();
            _tcpConsoleControl = tcpConsoleControl;
            _tcpClientTabHeader = tabHeader;
            DataContext = _currentConfig;
            
            // 更新TCP客户端状态显示
            UpdateTcpClientStatus();
            
            // 初始化升级状态机定时器
            InitializeUpgradeStateMachine();
        }

        /// <summary>
        /// 更新TCP客户端状态显示
        /// </summary>
        private void UpdateTcpClientStatus()
        {
            if (_tcpConsoleControl != null && !string.IsNullOrEmpty(_tcpClientTabHeader))
            {
                TcpClientNameTextBlock.Text = $"已连接: {_tcpClientTabHeader}";
                TcpClientStatusIndicator.Fill = FindResource("SuccessBrush") as System.Windows.Media.Brush;
            }
            else
            {
                TcpClientNameTextBlock.Text = "未绑定客户端";
                TcpClientStatusIndicator.Fill = FindResource("TextColor") as System.Windows.Media.Brush;
            }
        }

        /// <summary>
        /// 初始化升级状态机
        /// </summary>
        private void InitializeUpgradeStateMachine()
        {
            // 初始化升级状态机定时器
            _upgradeStateMachineTimer = new System.Windows.Threading.DispatcherTimer
            {
                Interval = TimeSpan.FromSeconds(1) // 每秒检查一次状态
            };
            _upgradeStateMachineTimer.Tick += UpgradeStateMachineTimer_Tick;
            _upgradeStateMachineTimer.IsEnabled = false;
            
            // 注册消息过滤器处理器，将cmd为996的JSON消息添加到ECU升级窗口的接收队列
            MessageFilter.RegisterHandler(_messageHandlerId, message =>
            {
                try
                {
                    EcuOtaManager.AddToReceivedQueue(message);
                    _receivedResponses.Add(message);
                }
                catch (Exception ex)
                {
                    // 这里可以添加错误日志记录
                    Console.WriteLine($"添加消息到ECU升级窗口接收队列失败: {ex.Message}");
                }
            });
        }

        /// <summary>
        /// 浏览文件按钮点击事件
        /// </summary>
        private void BrowseFileButton_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                OpenFileDialog openFileDialog = new OpenFileDialog
                {
                    Filter = "固件文件 (*.bin)|*.bin|所有文件 (*.*)|*.*",
                    Title = "选择固件文件"
                };

                if (openFileDialog.ShowDialog() == true)
                {
                    string filePath = openFileDialog.FileName;
                    _currentConfig.FilePath = filePath;
                    
                    // 获取文件信息
                    FileInfo fileInfo = new FileInfo(filePath);
                    string fileName = fileInfo.Name;
                    long fileSize = fileInfo.Length;
                    
                    // 显示文件信息
                FileNameTextBlock.Text = $"文件名称：{fileName}";
                
                // 格式化文件大小显示
                string sizeText;
                if (fileSize >= 1024 * 1024)
                {
                    sizeText = $"文件大小：{fileSize / (1024 * 1024.0):F2} MB";
                }
                else if (fileSize >= 1024)
                {
                    sizeText = $"文件大小：{fileSize / 1024.0:F2} KB";
                }
                else
                {
                    sizeText = $"文件大小：{fileSize} 字节";
                }
                FileSizeTextBlock.Text = sizeText;
                
                // 计算预计的总包数
                byte[] firmwareData = File.ReadAllBytes(filePath);
                int packetCount = (int)Math.Ceiling((double)firmwareData.Length / DATA_PACKET_SIZE);
                int totalJsonPackages = packetCount + 4; // 第三步包数 + 其他步骤包数(4个)
                _totalJsonPackageCount = totalJsonPackages; // 保存到成员变量中
                
                // 更新预计总包数显示
                this.Dispatcher.Invoke(() =>
                {
                    RemainingPacketsText.Text = totalJsonPackages.ToString();
                });
                
                // 保持UI更新
                this.Title = $"ECU OTA配置 - 已选择文件：{fileName} (预计{totalJsonPackages}包)";
            }
            }
            catch (Exception ex)
            {
                // 保持UI更新
                this.Title = $"ECU OTA配置 - 选择文件失败";
                Console.WriteLine($"选择文件失败：{ex.Message}");
            }
        }

        /// <summary>
        /// 固件升级按钮点击事件
        /// </summary>
        private void FirmwareUpgradeButton_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                // 检查是否已绑定TCP客户端
                if (_tcpConsoleControl == null || !_tcpConsoleControl.IsConnected || _tcpConsoleControl.TcpClientManager == null)
                {
                    this.Title = "ECU OTA配置 - 请先绑定TCP客户端";
                    return;
                }

                // 检查是否已选择固件文件
                if (string.IsNullOrEmpty(_currentConfig.FilePath) || !File.Exists(_currentConfig.FilePath))
                {
                    this.Title = "ECU OTA配置 - 请先选择固件文件";
                    return;
                }

                // 检查是否正在升级过程中
                if (_currentUpgradeState != FirmwareUpgradeState.Ready && 
                    _currentUpgradeState != FirmwareUpgradeState.Completed && 
                    _currentUpgradeState != FirmwareUpgradeState.Failed)
                {
                    this.Title = "ECU OTA配置 - 正在进行固件升级，请等待...";
                    return;
                }

                // 准备开始固件升级
                this.Title = "ECU OTA配置 - 开始固件升级...";
                FirmwareUpgradeButton.IsEnabled = false;
                BrowseFileButton.IsEnabled = false;
                _receivedResponses.Clear();
                
                // 记录升级开始时间
                _upgradeStartTime = DateTime.Now;
                // 读取固件文件的二进制数据
                _firmwareData = File.ReadAllBytes(_currentConfig.FilePath);
                
                // 计算第三步(SendingData)所需要的包数（每包256字节）
                _totalPacketCount = (int)Math.Ceiling((double)_firmwareData.Length / DATA_PACKET_SIZE);
                
                // 计算总JSON包数：第三步包数 + 其他步骤包数(4个)
                _totalJsonPackageCount = _totalPacketCount + 4;
                
                // 显示进度条区域并初始化进度条和状态信息
                this.Dispatcher.Invoke(() =>
                {
                    UpgradeProgressBar.Value = 0;
                    ProgressPercentageText.Text = "0%";
                    ElapsedTimeText.Text = "00:00:00";
                    RemainingTimeText.Text = "--:--:--";
                    SentPacketsText.Text = "0";
                    RemainingPacketsText.Text = _totalJsonPackageCount.ToString();
                });


                
                // 重置当前包索引
                _currentPacketIndex = 0;

                // 启动状态机
                _currentUpgradeState = FirmwareUpgradeState.NotifyingEcu;
                _upgradeStateMachineTimer.IsEnabled = true;

                // 发送通知ECU设备升级的命令
                SendOtaCommand(1); // 1表示通知升级
                this.Title = "ECU OTA配置 - 正在通知ECU设备升级...";
            }
            catch (Exception ex)
            {
                this.Title = "ECU OTA配置 - 启动固件升级失败";
                Console.WriteLine($"启动固件升级失败: {ex.Message}");
            }
        }

        /// <summary>
        /// 关闭按钮点击事件
        /// </summary>
        private void CloseButton_Click(object sender, RoutedEventArgs e)
        {
            this.Close();
        }

        /// <summary>
        /// 升级状态机定时器处理方法
        /// </summary>
        private void UpgradeStateMachineTimer_Tick(object? sender, EventArgs e)
        {
            try
            {
                // 定期更新已用时间和计算剩余时间
                this.Dispatcher.Invoke(() =>
                {
                    if (_currentUpgradeState != FirmwareUpgradeState.Ready && 
                        _currentUpgradeState != FirmwareUpgradeState.Completed && 
                        _currentUpgradeState != FirmwareUpgradeState.Failed)
                    {
                        // 计算已用时间
                        TimeSpan elapsedTime = DateTime.Now - _upgradeStartTime;
                        ElapsedTimeText.Text = $"{elapsedTime.Hours:D2}:{elapsedTime.Minutes:D2}:{elapsedTime.Seconds:D2}";
                        
                        // 计算当前已完成的JSON包数
                        int completedJsonPackages = 0;
                        double progress = 0;
                        
                        // 根据当前升级状态计算已完成的包数
                        if (_totalJsonPackageCount > 0)
                        {
                            switch (_currentUpgradeState)
                            {
                                case FirmwareUpgradeState.NotifyingEcu:
                                    completedJsonPackages = 0;
                                    progress = 0;
                                    break;
                                case FirmwareUpgradeState.ErasingFlash:
                                    completedJsonPackages = 1;
                                    progress = (double)completedJsonPackages / _totalJsonPackageCount;
                                    break;
                                case FirmwareUpgradeState.SendingData:
                                    completedJsonPackages = 1 + _currentPacketIndex;
                                    progress = (double)completedJsonPackages / _totalJsonPackageCount;
                                    break;
                                case FirmwareUpgradeState.VerifyingData:
                                    completedJsonPackages = 1 + _totalPacketCount;
                                    progress = (double)completedJsonPackages / _totalJsonPackageCount;
                                    break;
                                case FirmwareUpgradeState.Resetting:
                                    completedJsonPackages = 2 + _totalPacketCount;
                                    progress = (double)completedJsonPackages / _totalJsonPackageCount;
                                    break;
                            }
                        }
                        
                        // 更新进度条和百分比
                        int progressPercent = (int)(progress * 100);
                        UpgradeProgressBar.Value = progressPercent;
                        ProgressPercentageText.Text = $"{progressPercent}%";
                        
                        // 更新已发送包数和剩余包数
                        SentPacketsText.Text = $"{completedJsonPackages}";
                        RemainingPacketsText.Text = $"{_totalJsonPackageCount - completedJsonPackages}";
                        
                        // 计算剩余时间
                        if (progress > 0 && elapsedTime.TotalSeconds > 0)
                        {
                            double estimatedTotalTimeSeconds = elapsedTime.TotalSeconds / progress;
                            double remainingTimeSeconds = estimatedTotalTimeSeconds - elapsedTime.TotalSeconds;
                            
                            // 限制剩余时间不小于0
                            remainingTimeSeconds = Math.Max(0, remainingTimeSeconds);
                            
                            // 格式化剩余时间
                            int remainingHours = (int)remainingTimeSeconds / 3600;
                            int remainingMinutes = (int)(remainingTimeSeconds % 3600) / 60;
                            int remainingSeconds = (int)remainingTimeSeconds % 60;
                            
                            RemainingTimeText.Text = $"{remainingHours:D2}:{remainingMinutes:D2}:{remainingSeconds:D2}";
                        }
                        else
                        {
                            // 进度不足或时间太短，无法准确计算剩余时间
                            RemainingTimeText.Text = "--:--:--";
                        }
                    }
                });
                
                switch (_currentUpgradeState)
                {
                    case FirmwareUpgradeState.NotifyingEcu:
                        // 检查是否收到ECU的响应
                        bool needRetry;
                        if (HasReceivedResponse(1, out needRetry)) // 1是通知升级的响应标记
                        {
                            // 验证通过，进入下一个状态：擦除Flash
                            _currentUpgradeState = FirmwareUpgradeState.ErasingFlash;
                            _lastProcessedIndex = _receivedResponses.Count - 1; // 重置处理索引
                            _currentCommandRetryCount = 0; // 重置重试计数
                            SendOtaCommand(2); // 2表示擦除Flash
                            this.Title = "ECU OTA配置 - 正在擦除ECU设备Flash...";
                        }
                        else if (needRetry)
                        {
                            // result=0，需要重新发送命令
                            _currentCommandRetryCount++;
                            if (_currentCommandRetryCount <= MAX_RETRY_COUNT)
                            {
                                this.Title = "ECU OTA配置 - 重新发送通知ECU设备升级命令...";
                                SendOtaCommand(1); // 重新发送通知升级命令
                            }
                            else
                            {
                                // 超过最大重试次数，升级失败
                                _currentUpgradeState = FirmwareUpgradeState.Failed;
                                AppendToMessageLog("错误: 通知ECU设备升级失败，超过最大重试次数");
                            }
                        }
                        break;

                    case FirmwareUpgradeState.ErasingFlash:
                        // 检查是否收到ECU的响应
                        bool eraseNeedRetry;
                        if (HasReceivedResponse(2, out eraseNeedRetry)) // 假设2是擦除Flash的响应标记
                        {
                            // 进入下一个状态：下发数据流
                            _currentUpgradeState = FirmwareUpgradeState.SendingData;
                            _lastProcessedIndex = _receivedResponses.Count - 1; // 重置处理索引
                            _currentCommandRetryCount = 0; // 重置重试计数
                            SendOtaCommand(3); // 3表示下发数据流
                            this.Title = "ECU OTA配置 - 正在下发固件数据流...";
                        }
                        else if (eraseNeedRetry)
                        {
                            // 需要重新发送命令
                            _currentCommandRetryCount++;
                            if (_currentCommandRetryCount <= MAX_RETRY_COUNT)
                            {
                                this.Title = "ECU OTA配置 - 重新发送擦除ECU设备Flash命令...";
                                SendOtaCommand(2); // 重新发送擦除Flash命令
                            }
                            else
                            {
                                // 超过最大重试次数，升级失败
                                _currentUpgradeState = FirmwareUpgradeState.Failed;
                                AppendToMessageLog("错误: 擦除ECU设备Flash失败，超过最大重试次数");
                            }
                        }
                        break;

                    case FirmwareUpgradeState.SendingData:
                        // 检查是否收到ECU的响应
                        bool sendNeedRetry;
                        if (HasReceivedResponse(3, out sendNeedRetry)) // 假设3是数据流传输完成的响应标记
                        {
                            // 进入下一个状态：校验数据
                            _currentUpgradeState = FirmwareUpgradeState.VerifyingData;
                            _lastProcessedIndex = _receivedResponses.Count - 1; // 重置处理索引
                            _currentCommandRetryCount = 0; // 重置重试计数
                            SendOtaCommand(4); // 4表示校验数据
                            this.Title = "ECU OTA配置 - 正在校验数据...";
                        }
                        else if (sendNeedRetry)
                        {
                            // 需要重新发送命令
                            _currentCommandRetryCount++;
                            if (_currentCommandRetryCount <= MAX_RETRY_COUNT)
                            {
                                this.Title = "ECU OTA配置 - 重新发送固件数据流...";
                                SendOtaCommand(3); // 重新发送数据流命令
                            }
                            else
                            {
                                // 超过最大重试次数，升级失败
                                _currentUpgradeState = FirmwareUpgradeState.Failed;
                                AppendToMessageLog("错误: 下发固件数据流失败，超过最大重试次数");
                            }
                        }
                        break;

                    case FirmwareUpgradeState.VerifyingData:
                        // 检查是否收到ECU的响应
                        bool verifyNeedRetry;
                        if (HasReceivedResponse(4, out verifyNeedRetry)) // 假设4是数据校验完成的响应标记
                        {
                            // 进入下一个状态：复位
                            _currentUpgradeState = FirmwareUpgradeState.Resetting;
                            _lastProcessedIndex = _receivedResponses.Count - 1; // 重置处理索引
                            _currentCommandRetryCount = 0; // 重置重试计数
                            SendOtaCommand(5); // 5表示复位
                            this.Title = "ECU OTA配置 - 正在复位ECU设备...";
                        }
                        else if (verifyNeedRetry)
                        {
                            // 需要重新发送命令
                            _currentCommandRetryCount++;
                            if (_currentCommandRetryCount <= MAX_RETRY_COUNT)
                            {
                                this.Title = "ECU OTA配置 - 重新校验数据...";
                                SendOtaCommand(4); // 重新发送校验数据命令
                            }
                            else
                            {
                                // 超过最大重试次数，升级失败
                                _currentUpgradeState = FirmwareUpgradeState.Failed;
                                AppendToMessageLog("错误: 校验数据失败，超过最大重试次数");
                            }
                        }
                        break;

                    case FirmwareUpgradeState.Resetting:
                        // 检查是否收到ECU的响应
                        bool resetNeedRetry;
                        if (HasReceivedResponse(5, out resetNeedRetry)) // 假设5是复位完成的响应标记
                        {
                            // 升级完成
                        _currentUpgradeState = FirmwareUpgradeState.Completed;
                        _upgradeStateMachineTimer.IsEnabled = false;
                        FirmwareUpgradeButton.IsEnabled = true;
                        BrowseFileButton.IsEnabled = true;
                        this.Title = "ECU OTA配置 - 固件升级完成";
                        
                        // 更新进度条为100%和状态信息
                        this.Dispatcher.Invoke(() =>
                        {
                            UpgradeProgressBar.Value = 100;
                            ProgressPercentageText.Text = "100%";
                            TimeSpan totalTime = DateTime.Now - _upgradeStartTime;
                            ElapsedTimeText.Text = $"{totalTime.Hours:D2}:{totalTime.Minutes:D2}:{totalTime.Seconds:D2}";
                            RemainingTimeText.Text = "00:00:00";
                            SentPacketsText.Text = _totalJsonPackageCount.ToString();
                            RemainingPacketsText.Text = "0";
                        });
                        
                        // 显示升级完成弹窗并使其在最前面
                        MessageBox.Show(this, "固件升级完成！", "升级完成", MessageBoxButton.OK, MessageBoxImage.Information);
                        }
                        else if (resetNeedRetry)
                        {
                            // 需要重新发送命令
                            _currentCommandRetryCount++;
                            if (_currentCommandRetryCount <= MAX_RETRY_COUNT)
                            {
                                this.Title = "ECU OTA配置 - 重新复位ECU设备...";
                                SendOtaCommand(5); // 重新发送复位命令
                            }
                            else
                            {
                                // 超过最大重试次数，升级失败
                                _currentUpgradeState = FirmwareUpgradeState.Failed;
                                AppendToMessageLog("错误: 复位ECU设备失败，超过最大重试次数");
                            }
                        }
                        break;

                    case FirmwareUpgradeState.Failed:
                        // 升级失败
                        _upgradeStateMachineTimer.IsEnabled = false;
                        FirmwareUpgradeButton.IsEnabled = true;
                        BrowseFileButton.IsEnabled = true;
                        this.Title = "ECU OTA配置 - 固件升级失败";
                        
                        // 更新状态信息为失败状态
                        this.Dispatcher.Invoke(() =>
                        {
                            TimeSpan elapsedTime = DateTime.Now - _upgradeStartTime;
                            ElapsedTimeText.Text = $"{elapsedTime.Hours:D2}:{elapsedTime.Minutes:D2}:{elapsedTime.Seconds:D2}";
                            RemainingTimeText.Text = "--:--:--";
                            // 保留当前进度和包数信息，以便用户了解失败时的状态
                        });
                        
                        MessageBox.Show("固件升级失败，请重试！");
                        break;
                }
            }
            catch (Exception ex)
            {
                _currentUpgradeState = FirmwareUpgradeState.Failed;
                Console.WriteLine($"升级状态机执行异常: {ex.Message}");
            }
        }

        /// <summary>
        /// 在UI线程上更新消息日志
        /// </summary>
        /// <param name="message">要记录的消息</param>
        private void AppendToMessageLog(string message)
        {
            if (Dispatcher.CheckAccess())
            {
                // 直接在UI线程上执行
                MessageLogTextBox.AppendText($"[{DateTime.Now:HH:mm:ss}] {message}\n");
                // 滚动到底部
                MessageLogTextBox.ScrollToEnd();
            }
            else
            {
                // 在非UI线程上调用，需要使用Dispatcher
                Dispatcher.Invoke(() => AppendToMessageLog(message));
            }
        }

        /// <summary>
        /// 发送OTA命令
        /// </summary>
        /// <param name="commandType">命令类型</param>
        private async void SendOtaCommand(int commandType)
        {
            try
            {
                // 检查是否已绑定TCP客户端
                if (_tcpConsoleControl == null || !_tcpConsoleControl.IsConnected || _tcpConsoleControl.TcpClientManager == null)
                {
                    throw new Exception("未绑定TCP客户端或连接已断开");
                }

                // 构造JSON命令
                object commandObj;
                if (commandType == 1) // 通知ECU升级
                {
                    commandObj = new
                    {
                        cmd = 996, // OTA命令标识
                        script = 1 // 升级脚本标识
                    };
                }
                else if (commandType == 2) // 擦除Flash
                {
                    // 检查是否已选择固件文件
                    if (string.IsNullOrEmpty(_currentConfig.FilePath) || !File.Exists(_currentConfig.FilePath))
                    {
                        throw new Exception("未选择固件文件");
                    }
                      
                    // 获取文件大小
                    FileInfo fileInfo = new FileInfo(_currentConfig.FilePath);
                    long fileSize = fileInfo.Length;
                      
                    // 计算需要擦除的扇区数（1个扇区是4k字节）
                    const int SECTOR_SIZE = 4 * 1024; // 4KB扇区大小
                    int sectorCount = (int)Math.Ceiling((double)fileSize / SECTOR_SIZE);
                      
                    // 计算数据流下发包数（每包256字节）
                    const int PACKET_SIZE = 256; // 每包256字节
                    int cnt = (int)Math.Ceiling((double)fileSize / PACKET_SIZE);
                      
                    // 构造包含五个字段的JSON命令
                    commandObj = new
                    {
                        cmd = 996,       // OTA命令标识
                        script = 2,      // 升级脚本标识
                        size = fileSize, // bin文件的字节数
                        cnt = cnt,       // 数据流下发包数
                        sector = sectorCount // 需要擦除的扇区数
                    };
                }
                else if (commandType == 3) // 数据流下发
                {
                    // 截取当前包的数据（256字节）
                    int startIndex = _currentPacketIndex * DATA_PACKET_SIZE;
                    int dataLength = Math.Min(DATA_PACKET_SIZE, _firmwareData.Length - startIndex);
                    byte[] packetData = new byte[dataLength];
                    Array.Copy(_firmwareData, startIndex, packetData, 0, dataLength);

                    // 将byte[]转换为int数组以正确序列化JSON
                    int[] dataArray = new int[packetData.Length];
                    for (int i = 0; i < packetData.Length; i++)
                    {
                        dataArray[i] = packetData[i];
                    }

                    // 计算当前数据包的CRC16 Modbus校验值
                    int crcValue = CalculateCrc16Modbus(packetData);
                    
                    // 构造包含六个字段的JSON命令，添加length和crc字段
                    commandObj = new
                    {
                        cmd = 996,        // OTA命令标识
                        script = 3,       // 升级脚本标识
                        cnt = _currentPacketIndex, // 当前包索引（从0开始）
                        length = dataArray.Length, // data数组中的字节数
                        data = dataArray, // 数据包内容（256字节数组）
                        crc = crcValue    // 数据包的CRC16 Modbus校验值
                    };
                }
                else if (commandType == 4) // 数据校验
                {
                    // 计算整个固件数据的CRC16 Modbus校验值
                    int totalCrcValue = CalculateCrc16Modbus(_firmwareData);
                    
                    // 构造包含四个字段的JSON命令
                    commandObj = new
                    {
                        cmd = 996,         // OTA命令标识
                        script = 4,        // 升级脚本标识
                        size = _firmwareData.Length, // bin文件的总字节数
                        crc = totalCrcValue // bin文件的总CRC16 Modbus校验值
                    };
                }
                else if (commandType == 5) // 复位
                {
                    // 构造符合协议的复位命令
                    commandObj = new
                    {
                        cmd = 996,         // OTA命令标识
                        script = 5         // 升级脚本标识
                    };
                }
                else
                {
                    commandObj = new
                    {
                        cmd = 996, // OTA命令标识
                        type = commandType // 命令类型
                    };
                }
                string jsonCommand = JsonSerializer.Serialize(commandObj);

                // 发送命令
                bool sendResult = await _tcpConsoleControl.TcpClientManager.SendMessageAsync(jsonCommand, Encoding.UTF8);
                if (!sendResult)
                {
                    throw new Exception("发送命令失败");
                }

                Console.WriteLine($"发送OTA命令: {jsonCommand}");
                // 添加到消息日志
                AppendToMessageLog($"发送: {jsonCommand}");
            }
            catch (Exception ex)
            {
                _currentUpgradeState = FirmwareUpgradeState.Failed;
                Console.WriteLine($"发送OTA命令失败: {ex.Message}");
                // 添加错误信息到消息日志
                AppendToMessageLog($"错误: 发送命令失败 - {ex.Message}");
            }
        }

        /// <summary>
        /// 检查是否收到指定类型的响应
        /// </summary>
        /// <param name="responseType">响应类型</param>
        /// <param name="needRetry">输出参数，表示是否需要重试</param>
        /// <returns>是否收到成功响应</returns>
        private bool HasReceivedResponse(int responseType, out bool needRetry)
        {
            needRetry = false;
            try
            {
                // 只处理新收到的消息
                for (int i = _lastProcessedIndex + 1; i < _receivedResponses.Count; i++)
                {
                    string response = _receivedResponses[i];
                     
                    // 标记是否应该记录此消息
                    bool shouldLog = false;
                    bool matchedResponse = false;
                     
                    try
                    {
                        // 使用JsonSerializer进行更健壮的JSON解析
                        using (var document = JsonDocument.Parse(response))
                        {
                            var root = document.RootElement;
                               
                            // 检查是否是OTA命令响应 (cmd=996)
                            if (root.TryGetProperty("cmd", out var cmdProperty) && cmdProperty.GetInt32() == 996)
                            {
                                // 检查是否有script字段
                                if (root.TryGetProperty("script", out var scriptProperty))
                                {
                                    int script = scriptProperty.GetInt32();
                                    
                                    if (responseType == 1 && script == 1)
                                    {
                                        // 对于通知ECU升级命令 (script=1)
                                        matchedResponse = true;
                                        _lastProcessedIndex = i;
                                          
                                        if (root.TryGetProperty("result", out var resultProperty))
                                        {
                                            int result = resultProperty.GetInt32();
                                            if (result == 1)
                                            {
                                                shouldLog = true;
                                                return true; // 验证通过，进入下一个状态
                                            }
                                            else if (result == 0)
                                            {
                                                shouldLog = true;
                                                needRetry = true; // 需要重新发送命令
                                                return false;
                                            }
                                        }
                                    }
                                    else if (script == 4)
                                    {
                                        // 对于数据校验响应 (script=4)
                                        matchedResponse = true;
                                        _lastProcessedIndex = i;
                                          
                                        if (root.TryGetProperty("result", out var resultProperty) &&
                                            root.TryGetProperty("size", out var sizeProperty) &&
                                            root.TryGetProperty("crc", out var crcProperty))
                                        {
                                            int result = resultProperty.GetInt32();
                                            int receivedSize = sizeProperty.GetInt32();
                                            int receivedCrc = crcProperty.GetInt32();
                                              
                                            if (result == 1)
                                            {
                                                // 1. 校验size字段是否匹配固件大小
                                                if (receivedSize != _firmwareData.Length)
                                                {
                                                    // size不匹配，记录错误
                                                    shouldLog = true;
                                                    AppendToMessageLog($"错误: 固件大小校验失败，期望: {_firmwareData.Length}，实际: {receivedSize}");
                                                    _currentUpgradeState = FirmwareUpgradeState.Failed;
                                                    return false;
                                                }
                                                  
                                                // 2. 计算整个固件的CRC16 Modbus值并校验
                                                int calculatedCrc = CalculateCrc16Modbus(_firmwareData);
                                                if (receivedCrc != calculatedCrc)
                                                {
                                                    // CRC校验失败，记录错误
                                                    shouldLog = true;
                                                    AppendToMessageLog($"错误: 固件CRC校验失败，期望CRC: {calculatedCrc}，实际CRC: {receivedCrc}");
                                                    _currentUpgradeState = FirmwareUpgradeState.Failed;
                                                    return false;
                                                }
                                                  
                                                // size和crc双校验通过，数据校验成功
                                                shouldLog = true;
                                                return true; // 验证通过，进入下一个状态
                                            }
                                            else if (result == 0)
                                            {
                                                // 数据校验失败，直接退出升级状态
                                                shouldLog = true;
                                                _currentUpgradeState = FirmwareUpgradeState.Failed;
                                                AppendToMessageLog("错误: 数据校验失败");
                                                Console.WriteLine("数据校验失败");
                                                return false;
                                            }
                                        }
                                        else
                                        {
                                            // 响应消息缺少必要的字段
                                            shouldLog = true;
                                            AppendToMessageLog("错误: 数据校验响应缺少必要的字段");
                                            _currentUpgradeState = FirmwareUpgradeState.Failed;
                                            return false;
                                        }
                                    }
                                    else if (script == 2)
                                    {
                                        // 对于扇区擦除响应 (script=2)
                                        matchedResponse = true;
                                        _lastProcessedIndex = i;
                                          
                                        if (root.TryGetProperty("result", out var resultProperty))
                                        {
                                            int result = resultProperty.GetInt32();
                                            if (result == 1)
                                            {
                                                shouldLog = true;
                                                return true; // 验证通过，进入下一个状态
                                            }
                                            else if (result == 0)
                                            {
                                                // 扇区擦除失败，直接退出升级状态
                                                shouldLog = true;
                                                _currentUpgradeState = FirmwareUpgradeState.Failed;
                                                AppendToMessageLog("错误: 扇区擦除失败");
                                                Console.WriteLine("扇区擦除失败");
                                                return false;
                                            }
                                        }
                                    }
                                    else if (script == 5)
                                    {
                                        // 对于复位响应 (script=5)
                                        matchedResponse = true;
                                        _lastProcessedIndex = i;
                                          
                                        if (root.TryGetProperty("result", out var resultProperty))
                                        {
                                            int result = resultProperty.GetInt32();
                                            if (result == 1)
                                            {
                                                shouldLog = true;
                                                return true; // 验证通过，复位成功
                                            }
                                            else if (result == 0)
                                            {
                                                shouldLog = true;
                                                needRetry = true; // 需要重新发送命令
                                                return false;
                                            }
                                        }
                                    }
                                    else if (responseType == 3 && script == 3)
                                    {
                                        // 对于数据流下发响应 (script=3)
                                        matchedResponse = true;
                                        _lastProcessedIndex = i;
                                          
                                        if (root.TryGetProperty("result", out var resultProperty) && 
                                            root.TryGetProperty("cnt", out var cntProperty) && 
                                            root.TryGetProperty("crc", out var crcProperty))
                                        {
                                            int result = resultProperty.GetInt32();
                                            int receivedCnt = cntProperty.GetInt32();
                                            int receivedCrc = crcProperty.GetInt32();
                                              
                                            if (result == 1)
                                            {
                                                // 1. 校验cnt字段是否匹配当前发送的包索引
                                                if (receivedCnt != _currentPacketIndex)
                                                {
                                                    // cnt不匹配，记录错误并重试
                                                    shouldLog = true;
                                                    AppendToMessageLog($"错误: 数据包索引不匹配，期望: {_currentPacketIndex}，实际: {receivedCnt}");
                                                    needRetry = true;
                                                    return false;
                                                }
                                                  
                                                // 2. 计算当前发送数据包的CRC16 Modbus值并校验
                                                int startIndex = _currentPacketIndex * DATA_PACKET_SIZE;
                                                int dataLength = Math.Min(DATA_PACKET_SIZE, _firmwareData.Length - startIndex);
                                                byte[] currentPacketData = new byte[dataLength];
                                                Array.Copy(_firmwareData, startIndex, currentPacketData, 0, dataLength);
                                                int calculatedCrc = CalculateCrc16Modbus(currentPacketData);
                                                  
                                                if (receivedCrc != calculatedCrc)
                                                {
                                                    // CRC校验失败，记录错误并重试
                                                    shouldLog = true;
                                                    AppendToMessageLog($"错误: 数据包CRC校验失败，包索引: {_currentPacketIndex}，期望CRC: {calculatedCrc}，实际CRC: {receivedCrc}");
                                                    needRetry = true;
                                                    return false;
                                                }
                                                  
                                                // cnt和crc双校验通过，数据包接收成功
                                                _currentPacketIndex++;
                                                  
                                                // 计算当前已完成的JSON包数
                                                int completedJsonPackages = 1 + _currentPacketIndex;
                                                
                                                // 计算进度百分比
                                                int progress = (int)((double)completedJsonPackages / _totalJsonPackageCount * 100);
                                                this.Title = $"ECU OTA配置 - 正在发送固件数据... {progress}%";
                                                
                                                // 在UI线程上更新进度条和状态信息
                                                this.Dispatcher.Invoke(() =>
                                                {
                                                    // 进度更新将由定时器统一处理
                                                    // 这里只更新标题和日志，确保UI更新统一
                                                });
                                                  
                                                if (_currentPacketIndex % 10 == 0) // 每10包记录一次日志，避免日志过多
                                                {
                                                    AppendToMessageLog($"已发送 {_currentPacketIndex}/{_totalPacketCount} 包数据，进度: {progress}%");
                                                }
                                                  
                                                // 检查是否所有数据包都已发送完成
                                                if (_currentPacketIndex >= _totalPacketCount)
                                                {
                                                    shouldLog = true;
                                                    return true; // 所有数据发送完成，进入下一个状态
                                                }
                                                else
                                                {
                                                    // 还有数据包需要发送，继续发送下一包
                                                    SendOtaCommand(3);
                                                }
                                            }
                                            else if (result == 0)
                                            {
                                                // 数据包接收失败，需要重试
                                                shouldLog = true;
                                                AppendToMessageLog($"错误: 数据包 {_currentPacketIndex} 接收失败");
                                                needRetry = true;
                                                return false;
                                            }
                                        }
                                        else
                                        {
                                            // 响应消息缺少必要的字段
                                            shouldLog = true;
                                            AppendToMessageLog("错误: 数据流响应缺少必要的字段");
                                            needRetry = true;
                                            return false;
                                        }
                                    }
                                }
                                // 对于其他命令类型
                                else if (root.TryGetProperty("type", out var typeProperty) && typeProperty.GetInt32() == responseType)
                                {
                                    matchedResponse = true;
                                    _lastProcessedIndex = i;
                                      
                                    if (root.TryGetProperty("result", out var resultProperty))
                                    {
                                        string? result = resultProperty.GetString();
                                        if (result == "success")
                                        {
                                            shouldLog = true;
                                            return true;
                                        }
                                    }
                                }
                                // 对于其他类型的响应，只有在不是当前类型的重复响应时才记录
                                else if (!response.Contains($"\"type\":{responseType}") || response.Contains($"\"result\":1") || response.Contains($"\"result\":\"success\""))
                                {
                                    shouldLog = true;
                                }
                            }
                            else
                            {
                                // 非OTA命令响应，都记录
                                shouldLog = true;
                            }
                        }
                    }
                    catch (JsonException)
                    {
                        // 如果JSON解析失败，记录此消息并继续检查下一条响应
                        shouldLog = true;
                        continue;
                    }
                     
                    // 只有在需要记录时才添加到日志
                    if (shouldLog)
                    {
                        AppendToMessageLog($"[收←◆]{response}");
                    }
                     
                    // 如果是匹配的响应但没有返回，继续处理
                    if (matchedResponse)
                    {
                        _lastProcessedIndex = i;
                    }
                }
                return false;
            }
            catch (Exception ex)
            {
                Console.WriteLine($"检查响应失败: {ex.Message}");
                AppendToMessageLog($"错误: 检查响应失败 - {ex.Message}");
                return false;
            }
        }
        
        /// <summary>
        /// 计算CRC16 Modbus校验值
        /// </summary>
        /// <param name="data">要计算CRC的数据</param>
        /// <returns>CRC16校验值</returns>
        private static int CalculateCrc16Modbus(byte[] data)
        {
            const ushort polynomial = 0xA001; // Modbus CRC16多项式
            ushort crc = 0xFFFF; // 初始值
            
            foreach (byte b in data)
            {
                crc ^= b;
                for (int i = 0; i < 8; i++)
                {
                    bool bit = (crc & 1) == 1;
                    crc >>= 1;
                    if (bit)
                    {
                        crc ^= polynomial;
                    }
                }
            }
            
            // 将CRC转换为整数返回
            return crc;
        }
        
        // 兼容旧版本的重载方法
        private bool HasReceivedResponse(int responseType)
        {
            bool needRetry;
            return HasReceivedResponse(responseType, out needRetry);
        }

    }
}